const Koa = require('koa');

const app = new Koa();

app.use(async ctx => {
  if (ctx.method === 'GET' && ctx.url === '/') {
    ctx.body = `
      <h1>Koa2 request post</h1>
      <form action='/' method="POST">
        <p>userName</p>
        <input name="userName" />
        <p>age</p>
        <input name="age" />
        <p>website</p>
        <input name="website" />
        <p><button type="submit">提交</button></p>
      </form>
    `
  } else if (ctx.method === 'POST' && ctx.url === '/') {
    ctx.body = await getPostData(ctx);
  } else {
    ctx.body = '<h1>404!</h1>'
  }
})

function getPostData(ctx) {
  return new Promise((resolve, reject) => {
    try {
      let postData = '';
      ctx.req.on('data', (data) => {
        // on:data,这里都是在点击提交按钮的时候执行
        postData += data;
      })
      ctx.req.addListener('end', () => {
        // addListener:end,这里都是在点击提交按钮的时候执行
        resolve(parseData(postData));
      })
    } catch (error) {
      reject(error);
    }
  })
}

function parseData(postData) {
  const postDataObj = {};
  const postList = postData.split('&');
  // entries:转换为key/value的形式
  for (const [index, item] of postList.entries()) {
    const itemList = item.split('=');
    postDataObj[itemList[0]] = decodeURIComponent(itemList[1]);
  }
  return postDataObj;
}
app.listen(3030, () => {
  console.log('启动');
})